package org.zkoss.zk.ui;

import javax.servlet.ServletContext;

import org.ceva.training.persistence.bo.User;
import org.ceva.training.persistence.dao.UsersDAO;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zkplus.spring.SpringUtil;
public class LoginWindow  extends GenericForwardComposer {
	 private Textbox username;
	 private Textbox password;
	    
	public void onLogin(){		
		String strusername = username.getValue().trim();
		String strpassword = password.getValue().trim();
		User user = new User();
		user.setLoginname(strusername);
		user.setPassword(strpassword);
		ApplicationContext ctx = SpringUtil.getApplicationContext();
		UsersDAO userDAO = (UsersDAO) ctx.getBean("UsersDAO");		
		long id = userDAO.login(user);
		if(id==-1){
			try {
				Messagebox.show("Username "+user.getLoginname()+" does not exist . please register first!","Login Failed",Messagebox.OK,Messagebox.INFORMATION);
				username.setValue("");
				password.setValue("");
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
		}else if(id==-2){
			try {
				Messagebox.show("The password is not correct.","Login Failed",Messagebox.RETRY,Messagebox.INFORMATION);
				password.setValue("");
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
		}else {
			//this.detach();
			//Window contactWnd = (Window)Executions.createComponents("myContact.zul",null,null);
			//contactWnd.setAttribute("User",user);
			Executions.sendRedirect("home.zul");
		}
	}
	
	public void onRegister(){
		//this.detach();
		Executions.sendRedirect("register.zul");
		//Executions.createComponents("register.zul",null,null);
	}
}
